from typing import Any, Dict, List

from .base_node import BaseNode
from ..conditions.condition import ConditionEvaluator


class ConditionNode(BaseNode):
    """
    条件节点（单一职责：根据上下文与分支定义选择路由）。
    
    职责说明：
    - 读取 data.branches 配置并评估每个分支的条件
    - 优先命中第一个满足条件的分支；否则回退到 else 分支或第一个分支
    - 按选中的分支 id 寻找对应的出边并返回目标节点
    """
    def execute(self, graph: 'FlowGraph', context: Dict[str, Any], log: callable) -> List[str]:
        """
        执行条件判断并返回下一步要执行的节点列表。
        
        Args:
            graph ('FlowGraph'): 流程图对象
            context (Dict[str, Any]): 当前执行上下文
            log (callable): 日志记录函数
        
        Returns:
            List[str]: 下一步要执行的节点 ID 列表；若无匹配或无出边则返回空列表
        """
        branches = self.data.get('branches', []) or []
        selected_branch_id = None
        for br in branches:
            if ConditionEvaluator.eval_branch(br, context):
                selected_branch_id = br.get('id')
                log(f"[COND] Node {self.id} selected branch: {br.get('type')} ({selected_branch_id})")
                break
        if selected_branch_id is None:
            else_branch = next((b for b in branches if b.get('type') == 'else'), None)
            if else_branch:
                selected_branch_id = else_branch.get('id')
                log(f"[COND] Node {self.id} fallback to ELSE ({selected_branch_id})")
            elif branches:
                selected_branch_id = branches[0].get('id')
                log(f"[COND] Node {self.id} fallback to first branch ({selected_branch_id})")
            else:
                log(f"[COND] Node {self.id} has no branches; stopping.")
                return []
        for e in graph.get_outgoing_edges(self.id):
            if e.source_handle == selected_branch_id:
                return [e.target]
        log(f"[COND] Node {self.id} branch {selected_branch_id} has no outgoing edge; stopping.")
        return []